package org.irri.smta.domain;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "USER")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends TimestampedAutoIdEntity {

	private static final long serialVersionUID = 1L;

	@NotNull
	@Column(name = "USERNAME", nullable = false)
	@Size(min = 1, max = 50)
	private String username;

	@NotNull
	@Column(name = "PASSWORD", nullable = false)
	@Size(min = 1, max = 50)
	private String password;

	@ManyToOne(cascade = { CascadeType.DETACH, CascadeType.MERGE,
			CascadeType.PERSIST, CascadeType.REFRESH }, optional = false, fetch = FetchType.EAGER)
	@JoinColumn(name = "ROLE_ID")
	private Role role;

	@NotNull
	@Column(name = "ACTIVE", nullable = false)
	private Boolean active = true;

	private transient Boolean validPassword = Boolean.FALSE;
	private transient Integer passwordStrength = 0;
	private static final String MASK = "*";

	public User() {
		super();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = StringUtils.substring(username.trim(), 0, 50);
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = StringUtils.substring(password.trim(), 0, 50);
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public Boolean getActive() {
		return active;
	}

	public void setActive(Boolean active) {
		this.active = active;
	}

	public Boolean getValidPassword() {
		return validPassword;
	}

	public void setValidPassword(Boolean validPassword) {
		this.validPassword = validPassword;
	}

	public Integer getPasswordStrength() {
		return passwordStrength;
	}

	public void setPasswordStrength(Integer passwordStrength) {
		this.passwordStrength = passwordStrength;
	}

	public String getPasswordMask() {
		StringBuffer buffer = new StringBuffer();
		if (password != null) {
			for (Integer i = 0; i < password.length(); i++) {
				buffer.append(MASK);
			}
		}
		return buffer.toString();
	}

}
